StupidBeauty
Read times:1514Posted at:Thu Apr 19 05:39:35 2012
- no title specified

转载:注意 c++ vector中的erase()

std::vector的erase函数会返回被删除的元素的下一个元素的迭代器。

http://mashuai.blog.51cto.com/700343/267718

亮点:

如果要删除 4 7 两个元素

则删除 4 iterator 返回 5 ,不满足 if() 判断,这时 ++it 执行两次,一次是 else 里面,一次是 for() 循环里面,导致 7 被错过

实际上,应该是这样的

void fun()

{

vector <int> iVec;

vector <int>::iterator it;

for(int i=0;i<10;i++)

iVec.push_back(i);

display(iVec);

for(it=iVec.begin();it!=iVec.end();++it)

{

if(*it ==4 || *it == 7)

{

it=iVec. erase (it);

--it;// 这里回退一个

}

}

display(iVec);

}

Your opinions
Your name:Email:Website url:Opinion content:
- no title specified

HxLauncher: Launch Android applications by voice commands